#include "stdafx.h"
#include "ConfigLoaderSqlite.h"
#include "SQLite\DB_SQLite.h"
#include "Log\Log.h"

namespace woe
{
	ConfigLoaderSqlite::ConfigLoaderSqlite()
		:m_pSQLiteBase( NULL )
	{

	}

	ConfigLoaderSqlite::~ConfigLoaderSqlite()
	{
		if ( m_pSQLiteBase )
		{
			m_pSQLiteBase->Close();
			delete m_pSQLiteBase;
			m_pSQLiteBase = NULL;
		}
	}

	bool ConfigLoaderSqlite::DoLoad(const std::string& strDBName,  IConfigOperator* config)
	{	
		if ( !config )
		{
			LOG_DEBUG("Failed to , ConfigLoaderSqlite::DoLoad, the param config is NULL\n");
			return false;
		}
		if ( m_pSQLiteBase )
		{
			m_pSQLiteBase->Close();
			delete m_pSQLiteBase;
			m_pSQLiteBase = NULL;
		}
		m_pSQLiteBase = new CSQLiteBase;
		if ( !m_pSQLiteBase )
		{
			LOG_DEBUG("Failed to , ConfigLoaderSqlite::DoLoad, new CSQLiteBase failed\n");
			delete m_pSQLiteBase;
			m_pSQLiteBase = NULL;
			return false;
		}

		if ( !m_pSQLiteBase->Open( strDBName.c_str() ) )
		{
			LOG_DEBUG_V("Failed to Open db %s ,ConfigLoaderSqlite::DoLoad\n",strDBName.c_str());
			delete m_pSQLiteBase;
			m_pSQLiteBase = NULL;
			return false;	
		}
		CppSQLite3DB* db = m_pSQLiteBase->GetDB();
		if ( NULL == db )
		{
			LOG_DEBUG("Failed to Get DB ,ConfigLoaderSqlite::DoLoad\n");
			delete m_pSQLiteBase;
			m_pSQLiteBase = NULL;
			return false;
		}

		char szSQL[128] = "select name from sqlite_master where type = 'table' order by name";
		CppSQLite3Query query = db->execQuery(szSQL);

		while ( !query.eof() )
		{
			const char* szTblName = query.fieldValue(0);
			strcpy( szSQL, "select * from " );
			strcat_s( szSQL, szTblName );
			CppSQLite3Query query1 = db->execQuery(szSQL);
			while ( !query1.eof() )
			{
				//const char* sz1 = query1.fieldValue(0);
				//const char* sz2 = query1.fieldValue(1);
				CString strRet1, strRet2;
				m_pSQLiteBase->Transcode( query1.fieldValue( 0 ), strRet1 );
				m_pSQLiteBase->Transcode( query1.fieldValue( 1 ), strRet2 );
				//config->Set( sz1, sz2 );
				config->Set( strRet1.GetString(), strRet2.GetString() );
				query1.nextRow();
			}
			query.nextRow();	
		}
		return true;
	}
}